<?php
namespace app\common\model;

/**
 * 用户收货地址模型
 */
class Address extends BaseModel
{
    // 定义表名
    protected $name = 'address';

    // 定义主键
    protected $pk = 'address_id';

    // 追加字段
    protected $append = [];

    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->hasOne('app\\common\\model\\User');
    }
    
    /**
     * 获取列表
     */
    public function getList($search = '')
    {
        $search = trim($search);
        $model = $this->with(['user'])->order('address_id','desc');
        // 筛选条件
        $filter = [];
        if(!empty($search)){  
            //是否是数字
            if(is_numeric($search)){   
                //是否是手机号
                if(is_phone($search)){
                    $filter['phone'] = $search;
                }else{
                    $filter['user_id'] = $search;
                }
            }else{
               //不是数字   
                $model->where('name','like',"%{$search}%");
            }
        }
        // 执行查询
        return $model->where($filter)->paginate(['list_rows'=>15,'query' => request()->param()]);
    }

    /**
     * 新增收货地址
    */ 
    public function add(array $data, $user)
    {
        if(!is_phone($data['phone'])){
            $this->error = '手机号格式不对';
            return false;
        }
        // 添加收货地址
        $data['location'] = $data['locations'];
        $data['user_id'] = $user['user_id'];
        $data['applet_id'] = self::$applet_id;
        $this->save($data);
        // 设为默认收货地址
        !$user['address_id'] && $user->save(['address_id' => $this->address_id]);
        return true;
    }
    
    
    /**
     * 编辑地址
    */
    public function edit(array $data)
    {   
        if(!is_phone($data['phone'])){
            $this->error = '手机号格式不对';
            return false;
        }
        $data['location'] = $data['locations'];
        return $this->save($data) !== false;
    }

    /**
     * 设为默认收货地址
     */
    public function setDefault($user)
    {
        // 设为默认地址
        return $user->save(['address_id' => $this->address_id]);
    }

    /**
     * 删除收货地址
     */
    public function remove($user)
    {
        // 查询当前是否为默认地址
        $user['address_id'] == $this->address_id && $user->save(['address_id' => 0]);
        return $this->delete();
    }
}
